package com.shutuo.callnumqixintian;

import com.instwall.net.ApiBase;
import com.instwall.net.NetCore;
import com.instwall.net.NetCoreException;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import ashy.earl.common.util.L;
import okhttp3.Call;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class RequestApi extends ApiBase<String> {

    private PostBean postBean;

    public RequestApi(@NotNull PostBean postBean) {
        super("QiXinTian");
        this.postBean = postBean;
    }

    @Nullable
    @Override
    protected String requestApi(@NotNull NetCore netCore) throws Throwable {

        OkHttpClient okHttpClient = netCore.get().okHttp(NetCore.TIMEOUT);
        Call call = okHttpClient.newCall(getRequest());
        Response response =  call.execute();
        ResponseBody body = response.body();
        String msg = body == null ? "" : body.string();
        // Check response
        if (response.code() != 200) {
            throw new NetCoreException(NetCoreException.TYPE_SERVER, response.code(), msg, null, msg);
        }

        L.d(QixintianManager.TAG,QixintianManager.STAG + "onResponse : " + msg);
        return msg;
    }

    private Request getRequest(){

        RequestBody formBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("req",postBean.getReq())
                .addFormDataPart("appid",postBean.getAppid())
                .addFormDataPart("v","2.0")
                .addFormDataPart("ts",String.valueOf(postBean.getTime()))
                .addFormDataPart("sig",postBean.getSig())
                .addFormDataPart("fmt","JSON")
                .build();

        //2.创建Request对象
        Request request = new Request.Builder()
                .url("https://api.acewill.net/queue/showqueuereport")
                .post(formBody)
                .build();
        return request;
    }


}
